<?php
namespace App\Models;

use DB; 
use Illuminate\Database\Eloquent\Model;
use App\Models\TopicM;

class IconTopicM extends Model
{
    public static  $STable="lee_icon_topic";
    protected  $table="lee_icon_topic";
    
    protected $fillable = ['iconid', 'topicid'];
    
    /**
     * add icon-topic item
     * @param array $datas
     * formats [ ['iconid'=>1,'topicid'=>2],
     *           ['iconid'=>1,'topicid'=>3]  ]
     */
    static public function addItems(array $datas){
        $tbName=self::$STable;
        DB::table($tbName)->insert($datas);
    }
    
    
    /**
     * load all topics of one icon by it's id
     * @param unknown $icnID
     */
    static public function loadTpcByIcnID($icnFID){
        $icnTpcT=self::$STable;
        $tpcT=TopicM::$STable;
        
        $sql="select icnTpc.iconid as icnid,icnTpc.topicid  as tpcid,
              tpc.title as tpctitle
                FROM $icnTpcT as icnTpc 
                LEFT OUTER JOIN $tpcT as tpc
                on tpc.id=icnTpc.topicid
            where icnTpc.iconid=$icnFID";
        return DB::select($sql);
    }
    
    
    
    
    /**
     * load all topics of some icon ids
     * @param array $IconIDS
     */
    static  public function loadTpcByIcnIDS(array $IconIDS){
        $icnTpcT=self::$STable;
        $tpcT=TopicM::$STable;
        $icnFids=implode(',', $IconIDS);
        
        $sql="select icnTpc.iconid as icnid,icnTpc.topicid  as tpcid,
        tpc.title as tpctitle
        FROM $icnTpcT as icnTpc
        LEFT OUTER JOIN $tpcT as tpc
        on tpc.id=icnTpc.topicid
        where icnTpc.iconid in ( $icnFids ) ";
        return DB::select($sql);
    }
    
    /**
     * delete a icon-topic record
     * @param array $data
     * ['iconid'=>1,'topicid'=>3]
     */
    static  public function dltIcnTpc(array $data){
        self::where($data)->delete();
    }
    
    /***
     *  依据 icon的fid 删除相关 topic记录
     * @param unknown $iconfid
     */
    static public function dltTpcByIcn($iconfid){
        self::where('iconid',$iconfid)->delete();
    }
    
    /**
     * 依据topic的id返回其相关的IconID的集合
     * @param unknown $topicID
     */
    static public function getIconIDs($topicID,$lmt,$off){
        $IconTpcT=self::$STable;
        $sql="select iconid ,id from $IconTpcT where topicid = $topicID
             order by id DESC limit $lmt offset $off ";
        return DB::select($sql);
    }
    
    /**
     * 依据 icon的id 返回 相关的 topic id集合
     * @param unknown $iconid
     */
    static public function getTpcIDS($iconid){
           $coll= self::where('iconid',$iconid)->select('topicid')->get()->toArray();
            $rst=[];
           foreach ($coll as $item){
               array_push($rst, $item['topicid']);
           }
           return $rst;
    }
}

?>